// https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/?envType=study-plan-v2&envId=top-interview-150

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> index;
    TreeNode* myBuildTree(vector<int>& preorder, vector<int>& inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right) {
        if (preorder_left > preorder_right) {
            return nullptr;
        }
        // int preorder_root = preorder_left;
        // int inorder_root = index[preorder[preorder_left]];

        TreeNode* root = new TreeNode(preorder[preorder_left]);
        
        int leftLen = index[preorder[preorder_left]] - inorder_left;

        TreeNode* leftChild = myBuildTree(preorder, inorder, preorder_left + 1, preorder_left + leftLen, inorder_left, index[preorder[preorder_left]] - 1);
        TreeNode* rightChild = myBuildTree(preorder, inorder, preorder_left + leftLen + 1, preorder_right, index[preorder[preorder_left]] + 1, inorder_right);

        // root->left = myBuildTree(preorder, inorder, preorder_left + 1, preorder_left + leftLen, inorder_left, inorder_root - 1);
        // root->right = myBuildTree(preorder, inorder, preorder_left + leftLen + 1, preorder_right, inorder_root + 1, inorder_right);

        root->left = leftChild;
        root->right = rightChild;
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        for (int i = 0; i < n; i++) {
            index[inorder[i]] = i;
        }

        TreeNode* root = myBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
        return root;
    }
};